<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>SSE Chat Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        input, button { padding: 6px; margin: 5px; }
        #output {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
            background: #f9f9f9;
        }
        .input-group { margin: 10px 0; }
    </style>
</head>
<body>

<h2>SSE 聊天测试（一体化请求）</h2>

<div class="input-group">
    <label>Conversation ID: <input type="text" id="convId" value="test123" /></label><br/>
    <label>你的消息: <input type="text" id="userMsg" value="你好，请介绍一下你自己。" size="50"/></label><br/>
    <button onclick="startChat()">开始对话</button>
    <button onclick="clearOutput()">清空记录</button>
</div>

<div id="output"></div>

<script>
    let eventSource = null;
    let currentAiLineElement = null; // 用于追加当前 AI 回复
    let BASE_URL = "http://localhost:8080/chatTest"

    function logAsNewLine(role, text) {
        const output = document.getElementById('output');
        const line = document.createElement('div');
        line.innerHTML = `<strong>[${role}]:</strong> ${text}`;
        output.appendChild(line);
        output.scrollTop = output.scrollHeight;
        return line;
    }

    function appendToLastAiLine(text) {
        if (currentAiLineElement) {
            currentAiLineElement.innerHTML += text;
        } else {
            currentAiLineElement = logAsNewLine('AI', text);
        }
        document.getElementById('output').scrollTop = document.getElementById('output').scrollHeight;
    }

    function startChat() {
        const convId = document.getElementById('convId').value.trim();
        const msg = document.getElementById('userMsg').value.trim();

        if (!convId || !msg) {
            alert('请填写 Conversation ID 和消息');
            return;
        }

        if (eventSource) {
            eventSource.close();
        }

        const url = `${BASE_URL}/sse?conversationId=${encodeURIComponent(convId)}&msg=${encodeURIComponent(msg)}`;
        eventSource = new EventSource(url);

        // 显示用户消息（新行）
        logAsNewLine('你', msg);
        logAsNewLine('系统', '正在连接 AI...');

        eventSource.onopen = () => {
            logAsNewLine('状态', 'SSE 连接已建立，AI 开始生成...');
        };

        eventSource.onmessage = (e) => {
            const data = e.data;
            if (data === '[DONE]' || data === '[ERROR]') {
                currentAiLineElement = null; // 结束当前 AI 回复
                if (data === '[ERROR]') {
                    logAsNewLine('系统', 'AI 生成出错');
                }
                return;
            }
            appendToLastAiLine(data);
        };

        eventSource.onerror = (err) => {
            logAsNewLine('错误', 'SSE 连接失败或中断');
            eventSource.close();
            eventSource = null;
            currentAiLineElement = null;
        };
    }

    function clearOutput() {
        document.getElementById('output').innerHTML = '';
        currentAiLineElement = null;
    }
</script>

</body>
</html>
